#!/bin/bash

# 设置颜色输出
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m' # No Color

echo -e "${GREEN}=== BLESDK 最终运行脚本 ===${NC}"

# 导航到项目根目录
echo -e "${GREEN}导航到项目根目录...${NC}"
cd ~/Desktop/BLESDK

# 运行符号修复脚本
echo -e "${YELLOW}运行符号修复脚本...${NC}"
if [ -f "./fix_appdelegate.sh" ]; then
    chmod +x ./fix_appdelegate.sh
    ./fix_appdelegate.sh
else
    echo -e "${RED}fix_appdelegate.sh不存在，可能影响构建${NC}"
fi

# 运行验证脚本
echo -e "${YELLOW}运行BLESDK验证脚本...${NC}"
if [ -f "./verify_blesdk.sh" ]; then
    chmod +x ./verify_blesdk.sh
    ./verify_blesdk.sh
else
    echo -e "${RED}verify_blesdk.sh不存在，跳过验证步骤${NC}"
    
    # 导航到Example目录
    cd ~/Desktop/BLESDK/Example || { echo -e "${RED}无法找到Example目录${NC}"; exit 1; }
    
    # 安装依赖
    echo -e "${YELLOW}安装依赖...${NC}"
    pod install
fi

# 清理Xcode缓存
echo -e "${YELLOW}清理Xcode缓存...${NC}"
rm -rf ~/Library/Developer/Xcode/DerivedData/BLESDK*

# 尝试通过终端运行项目
echo -e "${GREEN}准备通过xcodebuild构建项目...${NC}"
cd ~/Desktop/BLESDK/Example

# 检查是否有可用设备
echo -e "${YELLOW}正在检查可用设备...${NC}"
DEVICE_ID=$(xcrun simctl list devices available | grep -m 1 "iPhone" | sed -E 's/.*\(([A-Za-z0-9-]+)\).*/\1/')

if [ -n "$DEVICE_ID" ]; then
    echo -e "${GREEN}找到可用设备: $DEVICE_ID${NC}"
    
    # 尝试构建并运行项目
    echo -e "${YELLOW}尝试构建项目...${NC}"
    xcodebuild -workspace BLESDK.xcworkspace -scheme BLESDK_Example -destination "platform=iOS Simulator,id=$DEVICE_ID" clean build | grep -v 'warning:'
    
    BUILD_RESULT=$?
    if [ $BUILD_RESULT -eq 0 ]; then
        echo -e "${GREEN}构建成功！正在启动模拟器...${NC}"
        open -a Simulator --args -CurrentDeviceUDID $DEVICE_ID
        
        echo -e "${YELLOW}正在安装并运行应用...${NC}"
        xcrun simctl install $DEVICE_ID ~/Library/Developer/Xcode/DerivedData/BLESDK*/Build/Products/Debug-iphonesimulator/BLESDK_Example.app
        xcrun simctl launch $DEVICE_ID com.cocoapods.BLESDK-Example
    else
        echo -e "${RED}构建失败，请通过Xcode手动运行${NC}"
    fi
else
    echo -e "${RED}未找到可用的模拟器设备${NC}"
fi

echo -e "${GREEN}=============================================${NC}"
echo -e "${GREEN}如果自动构建失败，请按照以下步骤在Xcode中运行:${NC}"
echo -e "${YELLOW}1. 打开BLESDK.xcworkspace (运行: open ~/Desktop/BLESDK/Example/BLESDK.xcworkspace)${NC}"
echo -e "${YELLOW}2. 选择BLESDK_Example目标${NC}"
echo -e "${YELLOW}3. 选择一个可用的模拟器或设备${NC}"
echo -e "${YELLOW}4. 选择菜单 Product > Clean Build Folder (Shift+Command+K)${NC}"
echo -e "${YELLOW}5. 点击运行按钮(▶)或按Command+R${NC}"
echo -e "${YELLOW}6. 如遇到权限提示，请允许蓝牙权限${NC}"
echo -e "${GREEN}=============================================${NC}" 